package my.action.authentication;
import java.util.ArrayList;

import javax.servlet.http.*;

import my.controller.*;
import my.db.DAO.ArticleDAO;
import my.db.DAO.AuthenticationDAO;
import my.db.DAO.AuthorDAO;
import my.db.DTO.ArticleDTO;
import my.db.DTO.AuthenticationDTO;
import my.db.DTO.AuthorDTO;
public class AuthenticationLoginAction implements  Action{
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		 //Field
		 	AuthenticationDAO autDAO=new AuthenticationDAO();
		   	ActionForward forward=new ActionForward();
		   	ArticleDAO adao=new ArticleDAO();
		   	String accountName=request.getParameter("user");
   			String accountPassword=request.getParameter("pwd");
   			AuthenticationDTO dto= new AuthenticationDTO();
   			AuthorDTO author=new AuthorDTO();
   			
   		//Checking condition
	   		try{   				   			
	   			dto=autDAO.loginAccount(accountName, accountPassword);
	   			if(dto==null){// if log in ==null call page login
	   				forward.setRedirect(false);
	   				forward.setPath("./login.jsp?error=Incorrect username or password");
	   			}else{
	   			// if log in success store session and checking position
	   				forward.setRedirect(true);
	   				HttpSession session=request.getSession(true);
	   				session.setAttribute("user", dto.getAccountName());// session account name
	   				session.setAttribute("userid", dto.getAutDTO().getAuthorID());//session author id
	   				session.setAttribute("userName",dto.getAutDTO().getAuthorName());// sessoin author name
	   				session.setAttribute("userGender",dto.getAutDTO().getAuthorGender());// session author gender
	   				session.setAttribute("userPhone",dto.getAutDTO().getAuthorPhone());// session author phone
	   				session.setAttribute("userMail",dto.getAutDTO().getAuthorMail());// session author email
	   				session.setAttribute("position", dto.getPosition());// sesson author position
	   				session.setAttribute("accountPwd", dto.getAccountPassword()); // session account password
	   				if(dto.getPosition().equals("admin")){
	   					forward.setPath("admin_load.jsp");
	   					forward.setRedirect(true);
	   				}else{
	   					forward.setPath("author_load.jsp");
	   					forward.setRedirect(true);
	   				}
	   			}
	  		}catch(Exception ex){
	  			System.out.println(ex);
	   		}
	  		return forward;
		}  	
}